package vn.com.demand.lux.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.DateFormat;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.NumberFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.criteria.WarrantyExpenseAccrualCriteria;
import vn.com.demand.lux.dao.WarrantyExpenseAccrualDao;
import vn.com.demand.lux.model.WarrantyExpenseAccrualBean;
import vn.com.demand.lux.view.contentprovider.WarrantyExpenseAccrualContentProvider;
import vn.com.demand.lux.view.labelprovider.WarrantyExpenseAccrualCalculatorLabelProvider;
import vn.com.demand.lux.view.labelprovider.WarrantyExpenseAccrualLabelProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.util.Validator;
import vn.com.demand.util.XMLUtils;
import vn.com.demand.widget.SearchableDialogActivator;
import vn.com.demand.widget.SelectItemCodeHeader;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;
/**
 * 
 * @author Huynh Tan Tai <httcntt@yahoo.com>
 *
 */
public class WarrantyExpenseAccrual extends ViewPart {
	
	private Button importButton;
	public static final String ID = "vn.com.demand.lux.view.WarrantyExpenseAccrual"; //$NON-NLS-1$
	private Table caculationTable;
	private Label dateLabel;
	private DateChooserCombo date;
	private Label machinePercentLabel;
	private Label accrualLedgerLabel;
	private Text division;
	private Text exchangeRate;
	private Text currency;
	private SearchableDialogActivator expenseLedger;
	private Text machineAccrualPercentage;
	private Text creditor;
	private SearchableDialogActivator resource;
	private SearchableDialogActivator accrualLedger;
	private SearchableDialogActivator journalCode;
	private Table detailTable;
	private DateChooserCombo fromDate;
	private DateChooserCombo toDate;
	private TableViewer detailTableViewer;
	private TableViewer caculationTableViewer;
	private static WarrantyExpenseAccrualCriteria warrantyExpenseCriteria;
	private List<WarrantyExpenseAccrualBean> warrantyList;
	private List<WarrantyExpenseAccrualBean> caculateResultList;
	private Button caculateButton;
	private FormattedText exchangeRateFormatText;
	private FormattedText machineFormatText;
	private Button xmlButton;
	private Button excelButton;
	public static final int ROUND_SCALE = 2;
	public static final int VND_ROUND_SCALE = 0;
	public static final int ROUND_MODE = BigDecimal.ROUND_HALF_UP;

	/**
	 * Create contents of the view part
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());
		toolkit.paintBordersFor(container);

		Label divisionLabel;

		Label fromDateLabel_2;

		// text = toolkit.createText(composite, null, SWT.NONE);
		Label creditorLabel;
		DateFormatter dateFormatter = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());
		DateFormatter dateFormatter2 = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());
		DateFormatter dateFormatter3 = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());

		SelectItemCodeHeader select2 = new SelectItemCodeHeader(null,
				"select * from DEMAND_JournalList");

		SelectItemCodeHeader select1 = new SelectItemCodeHeader(null,
				"select * from DEMAND_LedgerList");
		
		SelectItemCodeHeader select3 = new SelectItemCodeHeader(null,
		"select * from DEMAND_LedgerList");

		Section detailInformationSection;

		final Form luxPaymnetForm = toolkit.createForm(container);
		luxPaymnetForm.setText("Warranty Expense Accrual");
		final Composite body = luxPaymnetForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		final Section generalInformationSection = toolkit.createSection(body,
				Section.TITLE_BAR);
		final FormData fd_generalInformationSection = new FormData();
		fd_generalInformationSection.bottom = new FormAttachment(0, 135);
		fd_generalInformationSection.left = new FormAttachment(0, 5);
		fd_generalInformationSection.top = new FormAttachment(0, 0);
		fd_generalInformationSection.right = new FormAttachment(100, -5);
		generalInformationSection.setLayoutData(fd_generalInformationSection);
		generalInformationSection.setText("General Information");

		final Composite composite = new Composite(generalInformationSection,
				SWT.NONE);
		composite.setLayout(new FormLayout());
		toolkit.adapt(composite);
		generalInformationSection.setClient(composite);

		final Label fromDateLabel = toolkit.createLabel(composite,
				"From date:", SWT.NONE);
		final FormData fd_fromDateLabel = new FormData();
		fd_fromDateLabel.top = new FormAttachment(0, 6);
		fd_fromDateLabel.bottom = new FormAttachment(0, 26);
		fd_fromDateLabel.right = new FormAttachment(0, 67);
		fd_fromDateLabel.left = new FormAttachment(0, 0);
		fromDateLabel.setLayoutData(fd_fromDateLabel);
		fromDateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel
				.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		divisionLabel = toolkit.createLabel(composite,
				"Division:", SWT.NONE);
		final FormData fd_divisionLabel = new FormData();
		fd_divisionLabel.top = new FormAttachment(0, 32);
		fd_divisionLabel.bottom = new FormAttachment(0, 49);
		fd_divisionLabel.right = new FormAttachment(0, 67);
		fd_divisionLabel.left = new FormAttachment(0, 0);
		divisionLabel.setLayoutData(fd_divisionLabel);
		divisionLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		divisionLabel.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));
		fromDateLabel_2 = toolkit.createLabel(composite,
				"To date:", SWT.NONE);
		final FormData fd_fromDateLabel_2 = new FormData();
		fd_fromDateLabel_2.top = new FormAttachment(0, 6);
		fd_fromDateLabel_2.bottom = new FormAttachment(0, 26);
		fd_fromDateLabel_2.right = new FormAttachment(0, 315);
		fd_fromDateLabel_2.left = new FormAttachment(0, 225);
		fromDateLabel_2.setLayoutData(fd_fromDateLabel_2);
		fromDateLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		fromDateLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));
		creditorLabel = toolkit.createLabel(composite,
				"Miscellanous creditor:", SWT.NONE);
		final FormData fd_creditorLabel = new FormData();
		fd_creditorLabel.left = new FormAttachment(0, 225);
		fd_creditorLabel.top = new FormAttachment(0, 33);
		fd_creditorLabel.bottom = new FormAttachment(0, 50);
		fd_creditorLabel.right = new FormAttachment(0, 330);
		creditorLabel.setLayoutData(fd_creditorLabel);
		creditorLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		creditorLabel.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label fromDateLabel_1_1_1 = toolkit.createLabel(composite,
				"Journal code:", SWT.NONE);
		final FormData fd_fromDateLabel_1_1_1 = new FormData();
		fd_fromDateLabel_1_1_1.top = new FormAttachment(0, 57);
		fd_fromDateLabel_1_1_1.bottom = new FormAttachment(0, 71);
		fd_fromDateLabel_1_1_1.right = new FormAttachment(0, 67);
		fd_fromDateLabel_1_1_1.left = new FormAttachment(0, 0);
		fromDateLabel_1_1_1.setLayoutData(fd_fromDateLabel_1_1_1);
		fromDateLabel_1_1_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		fromDateLabel_1_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		fromDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_fromDate = new FormData();
		fd_fromDate.right = new FormAttachment(0, 175);
		fd_fromDate.bottom = new FormAttachment(0, 26);
		fd_fromDate.top = new FormAttachment(0, 6);
		fd_fromDate.left = new FormAttachment(0, 75);
		fromDate.setLayoutData(fd_fromDate);
		fromDate.setCapture(true);
		fromDate.setLayout(null);
		fromDate.setFormatter(dateFormatter);
		toolkit.adapt(fromDate);

		toDate = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_toDate = new FormData();
		fd_toDate.bottom = new FormAttachment(0, 27);
		fd_toDate.top = new FormAttachment(0, 6);
		fd_toDate.right = new FormAttachment(0, 470);
		fd_toDate.left = new FormAttachment(0, 370);
		toDate.setLayoutData(fd_toDate);
		toDate.setFormatter(dateFormatter2);
		toolkit.adapt(toDate);
		journalCode = new SearchableDialogActivator(composite, SWT.NONE,
				select2);
		final FormData fd_journalCode = new FormData();
		fd_journalCode.bottom = new FormAttachment(0, 80);
		fd_journalCode.top = new FormAttachment(0, 57);
		fd_journalCode.right = new FormAttachment(0, 175);
		fd_journalCode.left = new FormAttachment(0, 75);
		journalCode.setLayoutData(fd_journalCode);
		journalCode.setText("550");
		toolkit.adapt(journalCode);
		SelectItemCodeHeader accrualHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListAccrual");
		accrualLedger = new SearchableDialogActivator(composite, SWT.NONE,
				accrualHeader);
		final FormData fd_accrualLedger = new FormData();
		fd_accrualLedger.bottom = new FormAttachment(0, 106);
		fd_accrualLedger.top = new FormAttachment(0, 83);
		fd_accrualLedger.right = new FormAttachment(0, 470);
		fd_accrualLedger.left = new FormAttachment(0, 370);
		accrualLedger.setLayoutData(fd_accrualLedger);
		accrualLedger.setText("335008");
		toolkit.adapt(accrualLedger);

		final Label resourceLabel = toolkit.createLabel(composite, "Resource:", SWT.NONE);
		final FormData fd_resourceLabel = new FormData();
		fd_resourceLabel.top = new FormAttachment(0, 86);
		fd_resourceLabel.bottom = new FormAttachment(0, 100);
		fd_resourceLabel.right = new FormAttachment(0, 67);
		fd_resourceLabel.left = new FormAttachment(0, 0);
		resourceLabel.setLayoutData(fd_resourceLabel);
		resourceLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		resourceLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		SelectItemCodeHeader resourceHeader = new SelectItemCodeHeader(null, "select res_id as code , fullname as description from DEMAND_ResourceList");
		resource = new SearchableDialogActivator(composite, SWT.NONE, resourceHeader);
		final FormData fd_resource = new FormData();
		fd_resource.bottom = new FormAttachment(0, 106);
		fd_resource.top = new FormAttachment(0, 86);
		fd_resource.right = new FormAttachment(0, 175);
		fd_resource.left = new FormAttachment(0, 75);
		resource.setLayoutData(fd_resource);

		machinePercentLabel = toolkit.createLabel(composite, "Machine accrual percentage:", SWT.NONE);
		final FormData fd_machinePercentLabel = new FormData();
		fd_machinePercentLabel.left = new FormAttachment(0, 225);
		fd_machinePercentLabel.top = new FormAttachment(0, 58);
		fd_machinePercentLabel.bottom = new FormAttachment(0, 72);
		fd_machinePercentLabel.right = new FormAttachment(0, 369);
		machinePercentLabel.setLayoutData(fd_machinePercentLabel);
		machinePercentLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		machinePercentLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		creditor = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_creditor = new FormData();
		fd_creditor.bottom = new FormAttachment(0, 52);
		fd_creditor.top = new FormAttachment(0, 33);
		fd_creditor.right = new FormAttachment(0, 470);
		fd_creditor.left = new FormAttachment(0, 370);
		creditor.setLayoutData(fd_creditor);
		creditor.setText("99999999");

		accrualLedgerLabel = toolkit.createLabel(composite, "Accrual ledger:", SWT.NONE);
		final FormData fd_accrualLedgerLabel = new FormData();
		fd_accrualLedgerLabel.left = new FormAttachment(0, 225);
		fd_accrualLedgerLabel.top = new FormAttachment(0, 83);
		fd_accrualLedgerLabel.bottom = new FormAttachment(0, 100);
		fd_accrualLedgerLabel.right = new FormAttachment(0, 331);
		accrualLedgerLabel.setLayoutData(fd_accrualLedgerLabel);
		accrualLedgerLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		accrualLedgerLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		machineAccrualPercentage = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_machineAccrualPercentage = new FormData();
		fd_machineAccrualPercentage.bottom = new FormAttachment(0, 77);
		fd_machineAccrualPercentage.top = new FormAttachment(0, 58);
		fd_machineAccrualPercentage.right = new FormAttachment(0, 471);
		fd_machineAccrualPercentage.left = new FormAttachment(0, 371);
		machineAccrualPercentage.setLayoutData(fd_machineAccrualPercentage);
		machineFormatText = new FormattedText(machineAccrualPercentage);
		machineFormatText.setFormatter(new NumberFormatter("###"));
		machineFormatText.setValue(2);

		final Label expenseLedgerLabel = toolkit.createLabel(composite, "Expense ledger:", SWT.NONE);
		final FormData fd_expenseLedgerLabel = new FormData();
		fd_expenseLedgerLabel.left = new FormAttachment(0, 515);
		fd_expenseLedgerLabel.top = new FormAttachment(0, 33);
		fd_expenseLedgerLabel.bottom = new FormAttachment(0, 52);
		fd_expenseLedgerLabel.right = new FormAttachment(0, 600);
		expenseLedgerLabel.setLayoutData(fd_expenseLedgerLabel);
		expenseLedgerLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		expenseLedgerLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		
		SelectItemCodeHeader expenseHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListExpense");
		expenseLedger = new SearchableDialogActivator(composite, SWT.NONE, expenseHeader);
		expenseLedger.setText("641501");
		final FormData fd_expenseLedger = new FormData();
		fd_expenseLedger.bottom = new FormAttachment(0, 56);
		fd_expenseLedger.top = new FormAttachment(0, 33);
		fd_expenseLedger.right = new FormAttachment(0, 705);
		fd_expenseLedger.left = new FormAttachment(0, 605);
		expenseLedger.setLayoutData(fd_expenseLedger);
		toolkit.adapt(expenseLedger);

		currency = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_currency = new FormData();
		fd_currency.bottom = new FormAttachment(0, 81);
		fd_currency.top = new FormAttachment(0, 62);
		fd_currency.right = new FormAttachment(0, 705);
		fd_currency.left = new FormAttachment(0, 605);
		currency.setLayoutData(fd_currency);
		currency.setText("VND");

		final Label currencyLabel = toolkit.createLabel(composite, "Currency:", SWT.NONE);
		final FormData fd_currencyLabel = new FormData();
		fd_currencyLabel.left = new FormAttachment(0, 515);
		fd_currencyLabel.top = new FormAttachment(0, 62);
		fd_currencyLabel.bottom = new FormAttachment(0, 78);
		fd_currencyLabel.right = new FormAttachment(0, 582);
		currencyLabel.setLayoutData(fd_currencyLabel);
		currencyLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		currencyLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label exchangeRateLabel = toolkit.createLabel(composite, "Exchange rate:", SWT.NONE);
		final FormData fd_exchangeRateLabel = new FormData();
		fd_exchangeRateLabel.left = new FormAttachment(0, 515);
		fd_exchangeRateLabel.top = new FormAttachment(0, 87);
		fd_exchangeRateLabel.bottom = new FormAttachment(0, 104);
		fd_exchangeRateLabel.right = new FormAttachment(0, 590);
		exchangeRateLabel.setLayoutData(fd_exchangeRateLabel);
		exchangeRateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		exchangeRateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		exchangeRate = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_exchangeRate = new FormData();
		fd_exchangeRate.bottom = new FormAttachment(0, 107);
		fd_exchangeRate.top = new FormAttachment(0, 87);
		fd_exchangeRate.right = new FormAttachment(0, 705);
		fd_exchangeRate.left = new FormAttachment(0, 605);
		exchangeRate.setLayoutData(fd_exchangeRate);
		exchangeRateFormatText = new FormattedText(exchangeRate);
		exchangeRateFormatText.setFormatter(new NumberFormatter("###,###,###"));
		exchangeRateFormatText.setValue(1);

		division = toolkit.createText(composite, null, SWT.NONE);
		final FormData fd_division = new FormData();
		fd_division.bottom = new FormAttachment(0, 51);
		fd_division.top = new FormAttachment(0, 32);
		fd_division.right = new FormAttachment(0, 175);
		fd_division.left = new FormAttachment(0, 75);
		division.setLayoutData(fd_division);
		division.setText("530");

		date = new DateChooserCombo(composite, SWT.BORDER);
		final FormData fd_date = new FormData();
		fd_date.bottom = new FormAttachment(0, 27);
		fd_date.top = new FormAttachment(0, 6);
		fd_date.right = new FormAttachment(0, 705);
		fd_date.left = new FormAttachment(0, 605);
		date.setLayoutData(fd_date);
		date.setFormatter(dateFormatter3);
		date.setValue(new Date(System.currentTimeMillis()));
		toolkit.adapt(date);

		dateLabel = toolkit.createLabel(composite, "Date:", SWT.NONE);
		final FormData fd_dateLabel = new FormData();
		fd_dateLabel.top = new FormAttachment(0, 6);
		fd_dateLabel.bottom = new FormAttachment(0, 23);
		fd_dateLabel.right = new FormAttachment(0, 585);
		fd_dateLabel.left = new FormAttachment(0, 515);
		dateLabel.setLayoutData(fd_dateLabel);
		dateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		dateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		
		Composite buttonComposite;
		composite.setTabList(new Control[] {accrualLedgerLabel, machinePercentLabel, date, dateLabel});

		Composite composite_3;
		buttonComposite = new Composite(body, SWT.NONE);
		buttonComposite.setLayout(new FillLayout());
		final FormData fd_buttonComposite = new FormData();
		fd_buttonComposite.left = new FormAttachment(100, -620);
		fd_buttonComposite.top = new FormAttachment(100, -25);
		fd_buttonComposite.right = new FormAttachment(100, -5);
		fd_buttonComposite.bottom = new FormAttachment(100, -1);
		buttonComposite.setLayoutData(fd_buttonComposite);
		toolkit.adapt(buttonComposite);

		final Button refreshButton = new Button(buttonComposite, SWT.NONE);
		refreshButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/reload.png"));
		refreshButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				try {
					doRefesh();
					//Clean calculate table
					caculateResultList = null;
					caculationTableViewer.setInput(null);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});
		toolkit.adapt(refreshButton, true, true);
		refreshButton.setText("&Refresh");

		caculateButton = new Button(buttonComposite, SWT.NONE);
		caculateButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/mp3player.png"));
		caculateButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doCalculator();
			}
		});
		toolkit.adapt(caculateButton, true, true);
		caculateButton.setText("&Calculate");
		caculateButton.setEnabled(false);

		importButton = toolkit.createButton(buttonComposite, "Import", SWT.NONE);
		importButton.setEnabled(false);
		importButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doImportToExact();
			}
		});
		importButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileimport.png"));
		
		excelButton = toolkit.createButton(buttonComposite, "E&xport to Excel", SWT.NONE);
		excelButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/excel.gif"));
		excelButton.setEnabled(false);
		excelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2Excel();
			}
		});
		
		xmlButton = toolkit.createButton(buttonComposite, "Export to X&ML", SWT.NONE);
		xmlButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileexport.png"));
		xmlButton.setEnabled(false);
		xmlButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2XML();
			}
		});
		
		final Button closeButton = new Button(buttonComposite, SWT.NONE);
		closeButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		closeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				doClose();
			}
		});
		toolkit.adapt(closeButton, true, true);
		closeButton.setText("Clos&e");
		
		Composite detailComposite;
		detailComposite = toolkit.createComposite(body, SWT.BORDER);
		final FillLayout fillLayout = new FillLayout(SWT.VERTICAL);
		fillLayout.spacing = 10;
		detailComposite.setLayout(fillLayout);
		final FormData fd_detailComposite = new FormData();
		fd_detailComposite.top = new FormAttachment(0, 140);
		fd_detailComposite.bottom = new FormAttachment(100, -29);
		fd_detailComposite.right = new FormAttachment(100, -5);
		fd_detailComposite.left = new FormAttachment(0, 5);
		detailComposite.setLayoutData(fd_detailComposite);
		toolkit.paintBordersFor(detailComposite);
		detailInformationSection = toolkit.createSection(detailComposite,
				Section.TITLE_BAR);
		detailInformationSection.setText("Detail Information");

		final Composite composite_1 = toolkit.createComposite(
				detailInformationSection, SWT.NONE);
		composite_1.setLayout(new FillLayout());
		toolkit.paintBordersFor(composite_1);
		detailInformationSection.setClient(composite_1);

		detailTableViewer = new TableViewer(composite_1, SWT.BORDER);
		detailTable = detailTableViewer.getTable();
		detailTable.setLinesVisible(true);
		detailTable.setHeaderVisible(true);
		toolkit.adapt(detailTable, true, true);

		final TableColumn newColumnTableColumn = new TableColumn(detailTable,
				SWT.NONE);
		newColumnTableColumn.setWidth(104);
		newColumnTableColumn.setText("Contact Number");

		final TableColumn newColumnTableColumn_1 = new TableColumn(detailTable,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText("Type");

		final TableColumn newColumnTableColumn_2 = new TableColumn(detailTable,
				SWT.NONE);
		newColumnTableColumn_2.setWidth(118);
		newColumnTableColumn_2.setText("Cost Center");

		final TableColumn newColumnTableColumn_3 = new TableColumn(detailTable,
				SWT.NONE);
		newColumnTableColumn_3.setWidth(105);
		newColumnTableColumn_3.setText("Net Sales");

		final TableColumn newColumnTableColumn_6 = new TableColumn(detailTable,
				SWT.NONE);
		newColumnTableColumn_6.setWidth(161);
		newColumnTableColumn_6.setText("Accrual Amount This Month");
		
		detailTableViewer.setContentProvider(new WarrantyExpenseAccrualContentProvider());
		detailTableViewer.setLabelProvider(new WarrantyExpenseAccrualLabelProvider());

		final Section caculationResultSection = toolkit.createSection(detailComposite, Section.TITLE_BAR | Section.FOCUS_TITLE);
		caculationResultSection.setText("Caculation Result");
		composite_3 = new Composite(caculationResultSection, SWT.NONE);
		composite_3.setLayout(new FillLayout());
		caculationResultSection.setClient(composite_3);
		toolkit.adapt(composite_3);

		caculationTableViewer = new TableViewer(composite_3, SWT.BORDER);
		caculationTableViewer.setLabelProvider(new WarrantyExpenseAccrualCalculatorLabelProvider());
		caculationTableViewer.setContentProvider(new WarrantyExpenseAccrualContentProvider());
		caculationTable = caculationTableViewer.getTable();
		caculationTable.setLinesVisible(true);
		caculationTable.setHeaderVisible(true);
		toolkit.adapt(caculationTable, true, true);

		final TableColumn newColumnTableColumn_4 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_4.setWidth(66);
		newColumnTableColumn_4.setText("Date");

		final TableColumn newColumnTableColumn_1_1 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_1_1.setWidth(62);
		newColumnTableColumn_1_1.setText("Division");

		final TableColumn newColumnTableColumn_2_1 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_2_1.setWidth(63);
		newColumnTableColumn_2_1.setText("Journal");

		final TableColumn newColumnTableColumn_3_1 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_3_1.setWidth(52);
		newColumnTableColumn_3_1.setText("Number");

		final TableColumn newColumnTableColumn_5 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_5.setWidth(44);
		newColumnTableColumn_5.setText("Type");

		final TableColumn newColumnTableColumn_6_1 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_6_1.setWidth(65);
		newColumnTableColumn_6_1.setText("Sub Type");

		final TableColumn newColumnTableColumn_7 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_7.setWidth(56);
		newColumnTableColumn_7.setText("Ledger");

		final TableColumn newColumnTableColumn_8 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_8.setWidth(150);
		newColumnTableColumn_8.setText("Description");

		final TableColumn newColumnTableColumn_9 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_9.setWidth(65);
		newColumnTableColumn_9.setText("Creditor");

		final TableColumn newColumnTableColumn_10 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_10.setWidth(69);
		newColumnTableColumn_10.setText("Resource");

		final TableColumn newColumnTableColumn_11 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_11.setWidth(140);
		newColumnTableColumn_11.setText("YourReference");

		final TableColumn newColumnTableColumn_19 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_19.setWidth(60);
		newColumnTableColumn_19.setText("Currency");

		final TableColumn newColumnTableColumn_18 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_18.setWidth(90);
		newColumnTableColumn_18.setText("ExchangeRate");

		final TableColumn newColumnTableColumn_17 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_17.setWidth(60);
		newColumnTableColumn_17.setText("DebitFC");

		final TableColumn newColumnTableColumn_16 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_16.setWidth(60);
		newColumnTableColumn_16.setText("CreditFC");

		final TableColumn newColumnTableColumn_15 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_15.setWidth(70);
		newColumnTableColumn_15.setText("DebitVND");

		final TableColumn newColumnTableColumn_14 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_14.setWidth(70);
		newColumnTableColumn_14.setText("CreditVND");

		final TableColumn newColumnTableColumn_13 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_13.setWidth(80);
		newColumnTableColumn_13.setText("ProjectCode");

		final TableColumn newColumnTableColumn_12 = new TableColumn(caculationTable, SWT.NONE);
		newColumnTableColumn_12.setWidth(70);
		newColumnTableColumn_12.setText("CostCenter");

		createActions();
		initializeToolBar();
		initializeMenu();
	}

	protected void doImportToExact() {
		String fileLocation = Activator.getDefault().getAccountReceivableXMLLocation() + "\\WarrantyExpenseAccrual.xml";
		String serverNameParam = "-r" + Activator.getDefault().getDatabaseProperties()[0];
		String dbNameParam = "-D" + Activator.getDefault().getDatabaseProperties()[2];
		String urlParam;
		File file = new File(fileLocation);
		if (null != file) {
			try {
				Document document = buildDocument(caculateResultList);
				String tempFile = DpUtils.getTempFile("InterestSummaryXmlUnicodeRaw");
				XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(tempFile)));
				writer.write(document);
				writer.flush();
				writer.close();
				try {
					//get correct mapping file
					String xslMapping = Activator.getDefault()
							.getWarrantyAccrualXSLMapping();
						XMLUtils.transform(tempFile, xslMapping, file);
				} catch (Exception e) {
					MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check");
					return;
				}
			} catch (Exception e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}	
		urlParam = "-URL" + file.getAbsolutePath();
		String[] exactCommand = new String[] {"C:\\Program Files\\Exact Software\\bin\\asimport.exe", serverNameParam, dbNameParam,
				"-u", "-~", "I", urlParam, "-TGLENTRIES", "-0Auto"};
		try {
			Runtime.getRuntime().exec(exactCommand);
		} catch (IOException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
	
	}

	private void doRefesh() {
		if (doValidate()) {
			try {
				String fDate = fromDate.getText();
				String tDate = toDate.getText();
				String dateFormat = Activator.getDefault().getDateFormatTypePreferences();
				Date fromDate = DpUtils.parseDate(fDate, dateFormat);
				Date toDate = DpUtils.parseDate(tDate, dateFormat);
				//String issuing = issuingPurpose.getText();
				warrantyExpenseCriteria = new WarrantyExpenseAccrualCriteria();
				warrantyExpenseCriteria.setFromDate(fromDate);
				warrantyExpenseCriteria.setToDate(toDate);
				warrantyExpenseCriteria.setDate(DpUtils.parseDate(date.getText(), dateFormat));
				warrantyExpenseCriteria.setExpenseLedger(expenseLedger.getText().trim());
				warrantyExpenseCriteria.setAccrualLedger(accrualLedger.getText().trim());
				warrantyExpenseCriteria.setCurrency(currency.getText().trim());
				warrantyExpenseCriteria.setDivision(division.getText().trim());
				warrantyExpenseCriteria.setExchangeRate(((Number)exchangeRateFormatText.getValue()).doubleValue());
				warrantyExpenseCriteria.setJournalCode(journalCode.getText().trim());
				warrantyExpenseCriteria.setMachineAccrualPercentage(machineAccrualPercentage.getText().trim());
				warrantyExpenseCriteria.setMiscellanousCreditor(creditor.getText().trim());
				warrantyExpenseCriteria.setResource(resource.getText().trim());
				warrantyExpenseCriteria.setMachineAccrualPercentage(machineAccrualPercentage.getText().trim());
				warrantyList = WarrantyExpenseAccrualDao.searchWarrantyExpenseAccruals(warrantyExpenseCriteria);
				detailTableViewer.setInput(warrantyList);
				xmlButton.setEnabled(false);
				if (warrantyList == null || warrantyList.isEmpty()) {
					excelButton.setEnabled(false);
					caculateButton.setEnabled(false);
					MessageDialog.openInformation(null, "Information", "There is no data matched with those criteria");
				} else {
					excelButton.setEnabled(true);
					caculateButton.setEnabled(true);
				}
			} catch (Exception e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}
	}

	private void doCalculator() {
		try {
			caculateResultList = calculator(warrantyList, warrantyExpenseCriteria);
			caculationTableViewer.setInput(caculateResultList);
			if (caculateResultList == null || caculateResultList.isEmpty()) {
				xmlButton.setEnabled(false);
				importButton.setEnabled(false);
			} else {
				xmlButton.setEnabled(true);
				importButton.setEnabled(true);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
	}

	private void doClose() {
		this.getViewSite().getWorkbenchWindow().getActivePage().hideView(this);
	}

	public boolean doValidate() {
		Color orange = new Color(null, 255, 200, 100);
		Color white = new Color(null, 255, 255, 255);
		if (fromDate.getValue() == null) {
			MessageDialog.openError(null, "Error", "From date can not be empty");
			fromDate.setBackground(orange);
			fromDate.setFocus();
			return false;
		} else {
			fromDate.setBackground(white);
		}
		if (toDate.getValue() == null) {
			MessageDialog.openError(null, "Error", "To date can not be empty");
			toDate.setBackground(orange);
			toDate.setFocus();
			return false;
		} else {
			toDate.setBackground(white);
		}
		if (fromDate.getValue().after(toDate.getValue())) {
			MessageDialog.openError(null, "Error", "From date can not be after to date");
			toDate.setBackground(orange);
			toDate.setFocus();
			return false;
		} else {
			toDate.setBackground(white);
		}
		if (!Validator.isValidJournalCode(journalCode.getText().trim())) {
			MessageDialog.openError(null, "Error", "Journal code is not valid");
			journalCode.setBackground(orange);
			journalCode.setFocus();
			return false;
		} else {
			journalCode.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(accrualLedger.getText().trim())) {
			MessageDialog.openError(null, "Error","Accrual Ledger is not valid");
			accrualLedger.setBackground(orange);
			accrualLedger.setFocus();
			return false;
		} else {
			accrualLedger.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(expenseLedger.getText().trim())) {
			MessageDialog.openError(null, "Error","Expense Ledger is not valid");
			expenseLedger.setBackground(orange);
			expenseLedger.setFocus();
			return false;
		} else {
			expenseLedger.setBackground(white);
		}
		return true;
}
	
	private List<WarrantyExpenseAccrualBean> calculator(List<WarrantyExpenseAccrualBean> warrantyList, WarrantyExpenseAccrualCriteria criteria) {
		List<WarrantyExpenseAccrualBean> calculators = new ArrayList<WarrantyExpenseAccrualBean>();
		//Neu khong co detail nao co expense > 0 thi cung khong co dong nao o phan Caculation
		if (warrantyList == null || warrantyList.isEmpty() || sumWarrantyExpense(warrantyList) == 0) {
			return calculators;
		}
		//Add Calculate First Row Info
		addCalculatorFirstRow(calculators, warrantyList, criteria);
		int number = 2;
		for (int i = 0; i < warrantyList.size(); i++) {
			WarrantyExpenseAccrualBean w = warrantyList.get(i);
			if (w.getWarrantyExpense() > 0.0) {
				WarrantyExpenseAccrualBean w2 = new WarrantyExpenseAccrualBean();
				// Field Date
				w2.setDate(criteria.getDate());
				//Field Division
				w2.setDivision(criteria.getDivision());
				//Field Journal
				w2.setJournalCode(criteria.getJournalCode());
				//Field Number
				w2.setNumber(number++);
				//Field Type
				w2.setType("N");
				//Field Sub Type
				w2.setSubType("N");
				//Field Ledger
				w2.setLedger(criteria.getExpenseLedger());
				//Field Description
				String des = "Warranty accrual of ";
				String mm_yy = DpUtils.format(criteria.getToDate(), "MM/yyyy");
				des += mm_yy + ": Contract " + w.getContractNumber();
				w2.setDescription(des);
				//Field Customer
				w2.setCustomer(criteria.getMiscellanousCreditor());
				//Field Resource
				w2.setResource(criteria.getResource());
				//Field YourReference
				w2.setYourReference("WARRANTY_ACCRUAL");
				//Field Currency
				w2.setCurrency(criteria.getCurrency());
				//Field Exchange Rate
				w2.setExchangeRate(criteria.getExchangeRate());
				//Field DebitFC
				w2.setDebitFC(w.getWarrantyExpense()== null ? 0.0 : w.getWarrantyExpense());
				//Field CreditFC
				w2.setCreditFC(0.0); 
				//Field DebitVND
				double value = w2.getDebitFC() == null ? 0.0 : w2.getDebitFC();
				w2.setDebitVND(DpUtils.round(value * criteria.getExchangeRate() , VND_ROUND_SCALE, ROUND_MODE));
				//Field CreditVND
				value = w2.getCreditFC() == null ? 0.0 : w2.getDebitFC();
				w2.setCreditVND(DpUtils.round(value * criteria.getExchangeRate() , VND_ROUND_SCALE, ROUND_MODE));
				//Field Project Code
				w2.setProjectCode(w.getContractNumber());
				//Field CostCenter
				w2.setCostCenter(w.getCostCenter());
				calculators.add(w2);
			}
		}
		return calculators;
	}
	
	private double sumWarrantyExpense(List<WarrantyExpenseAccrualBean> warrantyList) {
		if (null == warrantyList || warrantyList.isEmpty()) {
			return 0;
		}
		double sum = 0;
		for (WarrantyExpenseAccrualBean bean : warrantyList) {
			sum += bean.getWarrantyExpense();
		}
		return sum;
	}

	private void addCalculatorFirstRow(List<WarrantyExpenseAccrualBean> calculators, List<WarrantyExpenseAccrualBean> warrantyList, WarrantyExpenseAccrualCriteria criteria) {
		WarrantyExpenseAccrualBean w = warrantyList.get(0);
		if (w.getWarrantyExpense() > 0.0) {
			WarrantyExpenseAccrualBean w2 = new WarrantyExpenseAccrualBean();
			// Field Date
			w2.setDate(criteria.getDate());
			//Field Division
			w2.setDivision(criteria.getDivision());
			//Field Journal
			w2.setJournalCode(criteria.getJournalCode());
			//Field Number
			w2.setNumber(1);
			//Field Type
			w2.setType("N");
			//Field Sub Type
			w2.setSubType("N");
			//Field Ledger
			w2.setLedger(criteria.getAccrualLedger());
			//Field Description
			String des = "Warranty accrual of ";
			String mm_yy = DpUtils.format(criteria.getToDate(), "MM/yyyy");
			des += mm_yy;
			w2.setDescription(des);
			//Field Customer
			w2.setCustomer(criteria.getMiscellanousCreditor());
			//Field Resource
			w2.setResource(criteria.getResource());
			//Field YourReference
			w2.setYourReference("WARRANTY_ACCRUAL");
			//Field Currency
			w2.setCurrency(criteria.getCurrency());
			//Field Exchange Rate
			w2.setExchangeRate(criteria.getExchangeRate());
			//Field DebitFC
			w2.setDebitFC(0.0);
			//Field CreditFC
			w2.setCreditFC(sumAccrualAmountThisMonth(warrantyList)); 
			//Field DebitVND
			double value = w2.getDebitFC() == null ? 0.0 : w2.getDebitFC();
			w2.setDebitVND(DpUtils.round(value * criteria.getExchangeRate() , VND_ROUND_SCALE, ROUND_MODE));
			//Field CreditVND
			value = w2.getCreditFC() == null ? 0.0 : w2.getDebitFC();
			w2.setCreditVND(DpUtils.round(value * criteria.getExchangeRate() , VND_ROUND_SCALE, ROUND_MODE));
			//Field Project Code
			w2.setProjectCode("");
			//Field CostCenter
			w2.setCostCenter("");
			calculators.add(w2);
		}
	}
	
	private Double sumAccrualAmountThisMonth(List<WarrantyExpenseAccrualBean> warrantyList) {
		Double sum = 0.0;
		for (int i = 0; i < warrantyList.size(); i++) {
			WarrantyExpenseAccrualBean w = warrantyList.get(i);
			if (w.getWarrantyExpense() != null) {
				sum += w.getWarrantyExpense();
			}
		}
		return sum;
	}
	
	private Document buildDocument(List<WarrantyExpenseAccrualBean> list) {
		String xmlDoubleFormat = new String("###############.00");
		double value = 0;
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("root");
		if (null != list && !list.isEmpty()) {
			for (WarrantyExpenseAccrualBean w : list) {
				Element row = root.addElement("row");
				row.addElement("Division").addText(w.getDivision());
				row.addElement("Date").addText(DpUtils.format(w.getDate()));
				row.addElement("DocumentDate").addText(DpUtils.format(w.getDate()));
				row.addElement("Journal").addText(w.getJournalCode());
				row.addElement("Number").addText(String.valueOf(w.getNumber()));
				row.addElement("SubType").addText(w.getSubType());
				row.addElement("Type").addText(w.getType());
				row.addElement("Ledger").addText(w.getLedger());
				row.addElement("Description").addText(w.getDescription());
				row.addElement("CostCenter").addText(w.getCostCenter());
				row.addElement("Customer").addText(w.getCustomer());
				row.addElement("Resource").addText(w.getResource());
				row.addElement("ProjectCode").addText(w.getProjectCode());
				
				value = DpUtils.round(w.getDebitVND(), ROUND_SCALE, ROUND_MODE);
				row.addElement("DebitVND").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value = DpUtils.round(w.getCreditVND(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditVND").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value = DpUtils.round(w.getDebitFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("DebitFC").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value = DpUtils.round(w.getCreditFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditFC").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				value = DpUtils.round(w.getExchangeRate(), ROUND_SCALE, ROUND_MODE);
				row.addElement("ExchangeRate").addText(value != 0 ? DpUtils.format(value, xmlDoubleFormat) : "0");
				
				row.addElement("Currency").addText(w.getCurrency());
				row.addElement("YourReference").addText(w.getYourReference());
			}
		}
		return document;
	}
	
	protected void doExport2XML() {
		if (null != caculateResultList && !caculateResultList.isEmpty()) {
			String fileLocation = getSavedFileLocation(new String[] {"XML File"}, new String[] {"*.xml"});
			File file = new File(fileLocation);
			if (null != file) {
				try {
					Document document = buildDocument(caculateResultList);
					String tempFile = DpUtils.getTempFile("InterestSummaryXmlUnicodeRaw");
					XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(tempFile)));
					writer.write(document);
					writer.flush();
					writer.close();
					try {
						//get correct mapping file
						String xslMapping = Activator.getDefault()
								.getWarrantyAccrualXSLMapping();
						if (file.exists()) {
							if (MessageDialog
									.openQuestion(null, "Question",
											"The file is existed, Do you want to overwrite it?")) {
								XMLUtils.transform(tempFile, xslMapping, file);
							}
						} else {
							XMLUtils.transform(tempFile, xslMapping, file);
						}
					} catch (Exception e) {
						MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check");
						return;
					}
					MessageDialog.openInformation(null, "Exportation completed", "The account receivable has been exported to XML format, please find at "
							+ file.getAbsolutePath());
				} catch (Exception e) {
					e.printStackTrace();
					MessageDialog.openError(null, "Error", e.getMessage());
				}
			}
		} else {
			MessageDialog.openWarning(null, "Warning", "The caculation result is empty, you can not export to xml file");
		}
	}
	
	private String getSavedFileLocation(String[] fileFilterNames, String[] fileFilterTypes) {
		FileDialog fileDialog = new FileDialog(this.getViewSite().getShell(), SWT.SAVE);
		fileDialog.setFilterExtensions(fileFilterTypes);
		fileDialog.setFilterNames(fileFilterNames);
		String reportLocation = fileDialog.open();
		return reportLocation;
	}
	
	protected void doExport2Excel() {
		String reportLocation = getSavedFileLocation(new String[] {"Excel files"}, new String[] {"*.xls"});
		if (null != reportLocation) {
			File file = new File(reportLocation);
			if (file.exists()) {
				if (MessageDialog.openQuestion(null, "Question", "The file is exists, Do you want to overwrite it?")) {
					doWriteExcelFile(file);
				}
			} else {
				doWriteExcelFile(file);
			}
		}

	}

	private void doWriteExcelFile(File file) {
		WritableWorkbook workbook;
		try {
			workbook = Workbook.createWorkbook(file);
			WritableSheet sheet = workbook.createSheet("Warranty Expense Accrual", 0);
			int contentBeginRow = setExcelReportHeader(sheet, 0);
			setExcelReportContent(sheet, contentBeginRow);
			workbook.write();
			workbook.close();
			if (MessageDialog.openQuestion(null, "Completed", "Export completed, click Ok to open the result file now or click Cancel to open it manually later")) {
				try {
					Runtime.getRuntime().exec("cmd.exe /C \"" + file.getAbsolutePath() + "\"");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RowsExceededException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
	}
	
	private int setExcelReportHeader(WritableSheet resultSheet, int row) {
		WritableCellFormat tf;
		WritableCellFormat numberFormat = new WritableCellFormat(NumberFormats.FLOAT);
		WritableFont criteriaFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
		WritableCellFormat criteriaFormat = new WritableCellFormat(criteriaFont);
		try {
			WritableFont title = new WritableFont(WritableFont.ARIAL, 20, WritableFont.BOLD);
			title.setColour(Colour.BLACK);
			tf = new WritableCellFormat(title);
			tf.setAlignment(Alignment.LEFT);
			//make title info
			resultSheet.addCell(new jxl.write.Label(0, row++, "Warranty Expense Accrual", tf));
			
			criteriaFont.setColour(Colour.BLUE);
			// add an empty row
			row++;
			// Criteria info
			WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableCellFormat boldFormat = new WritableCellFormat(font);
			boldFormat.setAlignment(Alignment.LEFT);
			
			WritableFont alinRightFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat alignRightCellFormat = new WritableCellFormat(alinRightFont);
			alignRightCellFormat.setAlignment(Alignment.RIGHT);
			
			resultSheet.addCell(new jxl.write.Label(0, row, "General Information", boldFormat));
			resultSheet.mergeCells(0, row, 1, row);
			row++;
			
			DateFormat format = new DateFormat(Activator.getDefault().getDateFormatTypePreferences());
			WritableCellFormat dateFormat = new WritableCellFormat(format);

			//1st header row
			resultSheet.addCell(new jxl.write.Label(0, row, "From date:", criteriaFormat));
			resultSheet.addCell(new jxl.write.DateTime(1, row, warrantyExpenseCriteria.getFromDate(), dateFormat));	
			resultSheet.addCell(new jxl.write.Label(2, row, "To date:", criteriaFormat));
			resultSheet.addCell(new jxl.write.DateTime(3, row, warrantyExpenseCriteria.getToDate(), dateFormat));
			row++;
			//2nd header row
			resultSheet.addCell(new jxl.write.Label(0, row, "Division:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, row, DpUtils.trim(warrantyExpenseCriteria.getDivision())));
			resultSheet.addCell(new jxl.write.Label(2, row, "Accrual ledger:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, row, DpUtils.trim(warrantyExpenseCriteria.getAccrualLedger())));
			row++;
			//3nd header row
			resultSheet.addCell(new jxl.write.Label(0, row, "Journal Code:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, row, DpUtils.trim(journalCode.getText())));
			resultSheet.addCell(new jxl.write.Label(2, row, "Expense ledger:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, row, DpUtils.trim(warrantyExpenseCriteria.getExpenseLedger())));
			row++;
			//4rd header row
			resultSheet.addCell(new jxl.write.Label(0, row, "Resource:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, row, warrantyExpenseCriteria.getResource()));
			resultSheet.addCell(new jxl.write.Label(2, row, "Currency:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(3, row, DpUtils.trim(warrantyExpenseCriteria.getCurrency())));
			row++;
			//5rd header row
			resultSheet.addCell(new jxl.write.Label(0, row, "Miscellanous creditor:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, row, DpUtils.trim(warrantyExpenseCriteria.getMiscellanousCreditor())));
			resultSheet.addCell(new jxl.write.Label(2, row, "Exchange rate:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(3, row, warrantyExpenseCriteria.getExchangeRate(), numberFormat));
			row++;
			//6rd header row
			resultSheet.addCell(new jxl.write.Label(0, row, "Machine accrual percentage:", criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, row, DpUtils.trim(warrantyExpenseCriteria.getMachineAccrualPercentage())));
			row++;
			//Detail row header
			WritableFont underLineFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat undeLineFontCellFormat = new WritableCellFormat(underLineFont);
			undeLineFontCellFormat.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, row++, "Detail Information", undeLineFontCellFormat));

			// set font and background color
			WritableFont header = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			header.setColour(Colour.WHITE);
			WritableCellFormat hf = new WritableCellFormat(header);
			hf.setBackground(Colour.BLUE);
			hf.setAlignment(Alignment.CENTRE);
			hf.setVerticalAlignment(VerticalAlignment.CENTRE);
			hf.setWrap(true);
			int col = 0;
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, row, "Contract Number", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, row, "Type", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet.addCell(new jxl.write.Label(col++, row, "Cost Center", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, row, "Net Sales", hf));
			resultSheet.setColumnView(col, 10);
			resultSheet.addCell(new jxl.write.Label(col++, row, "Accrual Amount this month", hf));
			resultSheet.setColumnView(col, 15);
			row++;
			return row;
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	private void setExcelReportContent(WritableSheet sheet, int row) {
		if (null != warrantyList && ! warrantyList.isEmpty()) {
			try {
				WritableCellFormat numberFormat = new WritableCellFormat(NumberFormats.FLOAT);
				int col = 0;
				for (WarrantyExpenseAccrualBean w : warrantyList) {
					sheet.addCell(new jxl.write.Label(col++, row, w.getContractNumber()));
					sheet.addCell(new jxl.write.Label(col++, row, w.getType()));
					sheet.addCell(new jxl.write.Label(col++, row, w.getCostCenter()));
					Double netSale = w.getNetSales() == null ? 0.0 : w.getNetSales();
					sheet.addCell(new jxl.write.Number(col++, row, netSale, numberFormat));
					Double amountThisMonth = w.getWarrantyExpense() == null ? 0.0 : w.getWarrantyExpense();
					sheet.addCell(new jxl.write.Number(col++, row, amountThisMonth, numberFormat));
					col = 0;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
		IToolBarManager toolbarManager = getViewSite().getActionBars()
				.getToolBarManager();
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
		IMenuManager menuManager = getViewSite().getActionBars()
				.getMenuManager();
	}

	@Override
	public void setFocus() {
		// Set the focus
	}

}
